package leetcode.leetcode_54;

import java.util.ArrayList;
import java.util.List;

class Solution {
    private final int[][] DIR = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    public List<Integer> spiralOrder(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;
        ArrayList<Integer> list = new ArrayList<>();
        int i = 0;
        int j = 0;
        int d = 0;
        for (int k = 0;k<m*n;k++){
            list.add(matrix[i][j]);
            int x = i + DIR[d][0];
            int y = j + DIR[d][1];
            matrix[i][j] = Integer.MAX_VALUE;
            if (x < 0 || x >= n || y < 0 || y >= m || matrix[x][y] == Integer.MAX_VALUE){
                d = (d + 1) % 4;
            }
            i = i + DIR[d][0];
            j = j + DIR[d][1];
        }
        return list;
    }
}